/*
 * @(#)CustomerTransactionFacade 1.0 2019/12/24
 *
 * Copyright 2019 JDJR All Rights Reserved.
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Author Email: zhangshaobo16@jd.com
 */
package com.bo.mvcframework.v2.servlet;

import com.bo.mvcframework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * 自建servlet类
 *
 * @description: 自建servlet类
 * @author: zhangshaobo16 on 2020/2/27.
 * @version： 2.0.0
 */
public class BoDispatcherServlet extends HttpServlet {

    /**
     * 配置信息
     */
    private Properties contextProperties = new Properties();

    /**
     * 扫描到的class名称
     */
    private List<String> classNames = new ArrayList<>();

    /**
     *  IOC容器
      */
    private Map<String, Object> ioc = new HashMap<>();

    /**
     * handleMapping
     */
    private Map<String, Method> handleMapping = new HashMap();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            this.doDispatcher(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception [" + e.getMessage() + "]");
        }
    }

    @Override
    public void init(ServletConfig config) {
        // 加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        // 扫描相关的类
        doScanner(contextProperties.getProperty("scanPackage"));
        // 初始化扫描到的类，并将他们放入ioc容器中
        doInstance();
        // 依赖注入
        doAutowired();
        // 初始化handlerMapping
        initHandleMapping();

        System.out.println("Bo Spring framework is init.");
    }

    private void initHandleMapping() {
        if (ioc.isEmpty()) {
            return ;
        }
        for (Object obj : ioc.values()) {
            Class<?> aClass = obj.getClass();
            // 判断是否是controller
            if (!aClass.isAnnotationPresent(BoController.class)) {
                continue;
            }
            String basrUrl = "";
            if(aClass.isAnnotationPresent(BoRequestMapping.class)){
                basrUrl = aClass.getAnnotation(BoRequestMapping.class).value();
            }
            // 获取controller下所有方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                // 如果方法是requestMapping方法
                if (method.isAnnotationPresent(BoRequestMapping.class)) {
                    // 获取方法的url链接
                    String value = method.getAnnotation(BoRequestMapping.class).value();
                    // url做key存入mapping。url与方法的对应关系
                    handleMapping.put(basrUrl+value, method);
                }
            }
        }

    }

    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }
        // 获取所有obj，依赖注入
        for (Object obj : ioc.values()) {
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                // 判断是否需要注入
                if (field.isAnnotationPresent(BoAutowired.class)) {
                    // 待注入的beanName
                    String beanName = field.getAnnotation(BoAutowired.class).value();
                    if ("".equals(beanName)) {
                        beanName = field.getType().getName();
                    }
                    field.setAccessible(true);
                    try {
                        field.set(obj, ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void doInstance() {
        // 如果classNames为空不需要加载
        if (classNames.isEmpty()) return;
        try {
            for (String clazzName : classNames) {
                if (!clazzName.contains(".")) {
                    return;
                }
                // 根据name获取class
                Class<?> aClass = Class.forName(clazzName);
                // 为了简单这里只做service和controller的加载，@Componmment、@Resptiory等同理
                if (aClass.isAnnotationPresent(BoController.class)) {
                    Object instance = aClass.newInstance();
                    // className作为beanName
                    String beanName = aClass.getName();
                    // 把class实例放入map中,controller的className与类实例的对应关系
                    ioc.put(beanName, instance);
                } else if(aClass.isAnnotationPresent(BoService.class)){
                    Object instance = aClass.newInstance();
                    String beanName = aClass.getAnnotation(BoService.class).value();
                    // 1. 自定义beanName
                    if ("".equals(beanName)) {
                        // 2. 默认使用类名作为beanName
                        beanName = aClass.getName();
                    }
                    ioc.put(beanName, instance);
                    // 3. 使用类型作为beanName
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        if (ioc.containsKey(anInterface.getName())) {
                            throw new Exception("The '" + anInterface.getName() + "' is exists!");
                        }
                        // 找到service的所有接口，接口名与实例的对应关系
                        ioc.put(anInterface.getName(), instance);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doLoadConfig(String contextConfigLocation) {
        // 获取到spring主配置文件所在的路径
        // 加载到properties中
        try(InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation)){
            contextProperties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doScanner(String scanPackage) {
        // 包名转换为path
        // 读取包下的所有文件。
        String name = "/" + scanPackage.replaceAll("\\.", "/");
        URL url = this.getClass().getClassLoader().getResource(name);
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()) {
            if(file.isDirectory()){
                doScanner(scanPackage+"."+file.getName());
            }
            if (!file.getName().endsWith(".class")) {
                continue;
            }
            String clazzName = scanPackage + "." + file.getName().replace(".class", "");
            classNames.add(clazzName);
        }
    }

    public void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 获取请求链接
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+","/");
        // 判断是否有对应的方法
        if (!this.handleMapping.containsKey(url)) {
            resp.setStatus(400);
            resp.getWriter().write("404 Not Found!");
            return ;
        }
        Method method = this.handleMapping.get(url);
        // 获取参数传入方法
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 执行方法
//        // 参数匹配度不够，无法动态匹配，只能强制获取name的值
//        method.invoke(this.ioc.get(method.getDeclaringClass().getName()), new Object[]{req,resp,parameterMap.get("name")[0]});
        // 获取方法所有的形参
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 创建形参对应的values数组
        Object[] paramValues = new Object[parameterTypes.length];

        // 获取方法参数param的所有注解
        Annotation[][] paAns = method.getParameterAnnotations();
        for (int i = 0; i < paAns.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            // 如果形参为request类型传入值
            if (parameterType == HttpServletRequest.class) {
                paramValues[i] = req;
            } else if (parameterType == HttpServletResponse.class){
                paramValues[i] = resp;
            } else {
                for (Annotation an : paAns[i]) {
                    // 取出所有的RequestParam注解
                    if (an instanceof BoRequestParam) {
                        String value = ((BoRequestParam) an).value();
                        // 取请求值，数组转换string并赋值给paramValues
                        String paramValue = Arrays.toString(parameterMap.get(value)).replaceAll("\\[|\\]","").replaceAll("\\s",",");
                        paramValues[i] = caseStringValue(paramValue, parameterType);
                    }
                }
            }
        }
//        for (int i = 0; i < parameterTypes.length; i++) {
//            Class<?> parameterType = parameterTypes[i];
//            // 如果形参为request类型传入值
//            if (parameterType == HttpServletRequest.class) {
//                paramValues[i] = req;
//            } else if (parameterType == HttpServletResponse.class){
//                paramValues[i] = resp;
//            } else {
//
//            }
//        }
        // 执行方法
        method.invoke(this.ioc.get(method.getDeclaringClass().getName()), paramValues);
    }

    /**
     * String转基础类型，没写全
     * @param paramValue
     * @param parameterType
     * @return
     */
    private Object caseStringValue(String paramValue, Class<?> parameterType) {
        if (parameterType == int.class) {
            return Integer.parseInt(paramValue);
        } else if (parameterType == Integer.class){
            return Integer.parseInt(paramValue);
        } else {
            return paramValue;
        }
    }


}
